{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TestBrain - 测试用例AI评审</title>
    <!-- 引入 Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <!-- 自定义样式 -->
    <style>
        body {
            padding: 20px;
            background-color: #f8f9fa;
        }
        .card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        }
        textarea {
            resize: vertical;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">测试用例AI评审</h5>
            </div>
            <div class="card-body">
                <form id="caseReviewForm">
                    <div class="form-group">
                        <label for="status">状态</label>
                        <select class="form-control" id="status" name="status">
                            <option value="pending">待评审</option>
                            <option value="approved">评审通过</option>
                            <option value="rejected">评审未通过</option>
                        </select>
                    </div>

                    <!-- 新增的三个下拉框，使用 Bootstrap 的栅格系统进行横向排列 -->
                    <div class="form-group">
                        <div class="row">
                            <div class="col-md-4">
                                <label for="bu">BU</label>
                                <select class="form-control" id="bu" name="bu">
                                    <option value="">请选择 BU</option>
                                    <option value="education">教育</option>
                                    <option value="user_center">用户中心</option>
                                    <option value="collaboration">协同</option>
                                    <option value="im">IM</option>
                                    <option value="workspace">工作台</option>
                                    <option value="recruitment">招聘</option>
                                    <option value="work_management">工作管理</option>
                                    <option value="ai_application">AI 应用</option>
                                    <option value="operation_platform">运营平台</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="feature">Feature</label>
                                <select class="form-control" id="feature" name="feature">
                                    <option value="">请选择 Feature</option>
                                    <option value="feature1">Feature1</option>
                                    <option value="feature2">Feature2</option>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label for="priority">Priority</label>
                                <select class="form-control" id="priority" name="priority">
                                    <option value="">请选择优先级</option>
                                    <option value="p0">P0</option>
                                    <option value="p1">P1</option>
                                    <option value="p2">P2</option>
                                    <option value="p3">P3</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="description">用例描述</label>
                        <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="test_steps">测试步骤</label>
                        <textarea class="form-control" id="test_steps" name="test_steps" rows="5"></textarea>
                    </div>
                    <div class="form-group">
                        <label for="expected_results">预期结果</label>
                        <textarea class="form-control" id="expected_results" name="expected_results" rows="5"></textarea>
                    </div>

                    <!-- 新增 AI 评审结果编辑框 -->
                    <div class="form-group">
                        <label for="ai_review_result">AI 评审结果</label>
                        <textarea class="form-control" id="ai_review_result" name="ai_review_result" rows="5" readonly></textarea>
                    </div>

                    <input type="hidden" id="test_case_id" name="test_case_id">
                </form>
            </div>
            <div class="card-footer text-right">
                <button type="button" class="btn btn-primary" id="startReviewBtn">开始评审</button>
                <button type="button" class="btn btn-success" id="saveBtn">保存</button>
            </div>
        </div>
    </div>

    <!-- 引入 jQuery 和 Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="{% static 'js/extra/bootstrap.bundle.min.js' %}"></script>
    
    <script>
    // 获取CSRF Token的辅助函数
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 页面加载完成后的初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 从URL获取测试用例ID并加载数据
        const urlParams = new URLSearchParams(window.location.search);
        const testCaseId = urlParams.get('id');
        
        if (testCaseId) {
            // 获取测试用例数据
            fetch(`/api/test-case/${testCaseId}/`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                }
            })
            .then(response => response.json())
            .then(data => {
                // 填充表单数据
                document.getElementById('test_case_id').value = data.id;
                document.getElementById('description').value = data.description;
                document.getElementById('test_steps').value = data.test_steps;
                document.getElementById('expected_results').value = data.expected_results;
                
                // 正确设置状态下拉框的值
                const statusSelect = document.getElementById('status');
                for(let i = 0; i < statusSelect.options.length; i++) {
                    if(statusSelect.options[i].value === data.status) {
                        statusSelect.selectedIndex = i;
                        break;
                    }
                }
                
                console.log('加载的状态值:', data.status);
            })
            .catch(error => {
                console.error('获取测试用例数据失败:', error);
                alert('获取测试用例数据失败，请查看控制台获取详细信息');
            });
        }

        // 开始评审按钮点击事件
        document.getElementById('startReviewBtn').onclick = function() {
            const testCaseId = document.getElementById('test_case_id').value;
            const aiReviewResult = document.getElementById('ai_review_result');
            const button = this;
            
            // 显示加载状态
            aiReviewResult.value = '评审中...';
            button.disabled = true;  // 禁用按钮防止重复点击
            
            fetch('/api/review/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    test_case_id: testCaseId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 先更新文本框内容
                    aiReviewResult.value = data.review_result;
                    // 使用 Promise 和 setTimeout 确保 DOM 更新后再显示提示
                    return new Promise(resolve => {
                        setTimeout(() => {
                            alert('AI评审完成！');
                            resolve();
                        }, 0);
                    });
                } else {
                    aiReviewResult.value = '评审失败：' + data.message;
                    alert('评审失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('评审请求失败:', error);
                aiReviewResult.value = '评审请求失败，请查看控制台获取详细信息';
                alert('评审请求失败，请查看控制台获取详细信息');
            })
            .finally(() => {
                button.disabled = false;  // 恢复按钮可用状态
            });
        };

        // 保存按钮点击事件
        document.getElementById('saveBtn').onclick = function() {
            const form = document.getElementById('caseReviewForm');
            const formData = {
                test_case_id: form.test_case_id.value,
                status: form.status.value,
                bu: form.bu.value,
                feature: form.feature.value,
                priority: form.priority.value,
                description: form.description.value,
                test_steps: form.test_steps.value,
                expected_results: form.expected_results.value
            };

            fetch('/api/update-test-case/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify(formData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('保存成功！');
                    window.close();
                    window.opener.location.reload();
                } else {
                    alert('保存失败：' + data.message);
                }
            })
            .catch(error => {
                console.error('保存失败:', error);
                alert('保存失败，请查看控制台获取详细信息');
            });
        };

        // 初始化 Feature 下拉框
        initFeatureSelect();
    });

    // Feature 下拉框初始化
    function initFeatureSelect() {
        const featureSelect = document.getElementById('feature');
        
        const addNewOption = document.createElement('option');
        addNewOption.value = 'add_new';
        addNewOption.textContent = '+ 添加新 Feature';
        featureSelect.appendChild(addNewOption);

        // 监听选择变化
        featureSelect.addEventListener('change', function() {
            if (this.value === 'add_new') {
                const newFeature = prompt('请输入新的 Feature 名称：');
                if (newFeature && newFeature.trim()) {
                    // 创建新的选项
                    const option = document.createElement('option');
                    option.value = newFeature.toLowerCase().replace(/\s+/g, '_');
                    option.textContent = newFeature;
                    
                    // 插入到倒数第二个位置（在"添加新 Feature"选项之前）
                    featureSelect.insertBefore(option, addNewOption);
                    
                    // 选中新添加的选项
                    this.value = option.value;
                } else {
                    // 如果用户取消或输入为空，恢复到默认选项
                    this.value = '';
                }
            }
        });
    }
    </script>
</body>
</html> 